<?php
/**
 * Created by KLXQ
 * user: youyi
 * Date：2024/6/5  11:47.
 * Tencent SDK.
 * 目前主要用于获取用户签名.
 */

namespace App\Http\Helpers\Tencent;

use Tencent\TLSSigAPIv2;

class SignTencent
{
    private int $sdkAppId;
    private string $sdkSecretKey;

    public function __construct()
    {
        $this->sdkAppId = config('tencent.trtc.app_id');
        $this->sdkSecretKey = config('tencent.trtc.secret_key');
    }

    // 签名
    public function genUserSign($identifier, $expire = 86400 * 180): string
    {
        try {
            $api = new TLSSigAPIv2($this->sdkAppId, $this->sdkSecretKey);

            return $api->genSig($identifier, $expire);
        } catch (\Exception $e) {
            echo $e;
        }
    }

    /**
     * userbuf签名.
     */
    public function genSigWithUserBuf($identifier, $expire, $userbuf): string
    {
        try {
            $api = new TLSSigAPIv2($this->sdkAppId, $this->sdkSecretKey);

            return $api->genSigWithUserBuf($identifier, $expire, $userbuf);
        } catch (\Exception $e) {
            echo $e;
        }
    }

    public function verifySigWithUserBuf($sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg)
    {
        try {
            $api = new TLSSigAPIv2($this->sdkAppId, $this->sdkSecretKey);

            return $api->verifySigWithUserBuf($sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg);
        } catch (\Exception $e) {
            echo $e;
        }
    }

    /**
     * 批量用户生成签名.
     *
     * @return array
     */
    public function genUserSigns($userIds, $expire)
    {
        $retData = [];
        foreach ($userIds as $id) {
            $retData[$id] = $this->genUserSign($id, $expire);
        }

        return $retData;
    }
}
